package org.budo.jdbc.driver.resultset.impl;

import java.io.Closeable;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.Map;

import org.budo.jdbc.driver.AbstractBudoJdbcResultSet;
import org.budo.support.lang.util.IoUtil;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

/**
 * @author lmw
 */
@Getter
@Setter
@NoArgsConstructor
public class IteratorResultSet extends AbstractBudoJdbcResultSet {
    private Iterator<?> iterator;

    private Object next;

    private Integer rowNumber = -1;

    public IteratorResultSet(ResultSetMetaData metaData, Iterator<?> iterator) {
        this.setMetaData(metaData);
        this.setIterator(iterator);
    }

    public void close() throws SQLException {
        if (iterator instanceof Closeable) {
            IoUtil.close((Closeable) iterator);
        }
    }

    public boolean next() throws SQLException {
        if (this.rowNumber < 0 && null != this.next) {
            this.rowNumber++;
            return true;
        }

        if (iterator.hasNext()) {
            this.rowNumber++;
            this.next = iterator.next();
            return true;
        }

        return false;
    }

    @Override
    protected Object getColumnValueRaw(String columnLabel) {
        Map<?,?> next = (Map<?,?>) this.getNext();
        Object value = next.get(columnLabel);
        if (null == value) {
            this.setLastValueWasNull(true);
        }

        return value;
    }
}